﻿using System;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Collections.Generic;



public partial class Main_Reports_ServiceInvoice_InvoiceViews_ClientLedgers : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    AccountSettings acntstng = new AccountSettings();
    DataTable dtMn = new DataTable();
    DataTable dtCustmr = new DataTable();
    DataTable dtMain1 = new DataTable();
    DataTable dtMain = new DataTable();
    string finyear = string.Empty;
    string previousBill = string.Empty;
    int firstRow = 0;
    
    int ds = 0;
    string lid = string.Empty;
    string lname = string.Empty;
    double dblNetClosing = 0;
    double dblNetClosingN = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            BindCustomer();
            pnlTDSClient.Visible = true;
            pnlGrid.Visible = false;
            lblCompName.Text = Session["compname"].ToString();
        }
    }

    protected void BindGrid()
    {
        SqlParameter[] sqlparam = {
                                      new SqlParameter("@Finyear",hidfinyear.Value.ToString()),
                                      new SqlParameter("@FROMDATE",string.Format("{0:MM/dd/yyyy}",Convert.ToDateTime(txtFromDate.Text))),
                                      new SqlParameter("@TODATE",string.Format("{0:MM/dd/yyyy}",Convert.ToDateTime(txtToDate.Text))),
                                      new SqlParameter("@LEDGERLIST",lid)
                                  };

        dtMn = DU.getdatausingprocedure("USP_IVC_GetClientLedgerDetails", sqlparam);
        grdClientLedgerView.DataSource = dtCustmr;
        grdClientLedgerView.DataBind();
     //   DataList2.DataSource = dtCustmr;
     //   DataList2.DataBind();
    }

    protected void BindCustomer()
    {
        dtMain = DU.getdatausingprocedure("USP_IVC_GetCustomerLedger");
        grdTDSClient.DataSource = dtMain;
        grdTDSClient.DataBind();
    }

    protected void grdClientLedgerView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdClientLedgerView.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void grdClientLedgerView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        dblNetClosing = 0;
        previousBill = string.Empty;                         
        firstRow = 1;
        string [] custID=lid.Split(',');
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ds++;
            if (custID.Length > ds)
            {
                Label d = (Label)e.Row.FindControl("lblCustomerName");
                d.Text = dtCustmr.Rows[ds-1]["LNAME"].ToString();
              
                GridView grdChild = new GridView();
                grdChild.AutoGenerateColumns = false;
                grdChild.Width = Unit.Percentage(100);
                //grdChild.CssClass = "gridview";
                grdChild.ShowHeader = true;
                string[] strKeyValue = { "Sortorder2" };
                grdChild.DataKeyNames = strKeyValue;
                grdChild.RowDataBound += new GridViewRowEventHandler(grdChild_RowDataBound);

                grdChild.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                //grdChild.HeaderStyle.CssClass = "headtd";
                //grdChild.BorderColor = System.Drawing.Color.Black;
                BoundField Date = new BoundField();
                Date.DataField = "Date";
                Date.ItemStyle.Width = Unit.Percentage(12);
                //Type.ItemStyle.Wrap = true;
                Date.DataFormatString = "{0:dd/MMM/yyyy}";
                Date.HeaderText = "Date";
                grdChild.Columns.Add(Date);
                BoundField Particulars = new BoundField();
                Particulars.DataField = "Particulars";
                Particulars.ItemStyle.Width = Unit.Percentage(38);
                // PartyName.ItemStyle.Wrap = true;
                Particulars.HeaderText = "Particulars";
                grdChild.Columns.Add(Particulars);
                BoundField DebitAmount = new BoundField();
                DebitAmount.DataField = "Dr";
                DebitAmount.ItemStyle.Width = Unit.Percentage(15);
                // billnumber.ItemStyle.Wrap = true;
                DebitAmount.HeaderText = "Debit";
                DebitAmount.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                grdChild.Columns.Add(DebitAmount);
                BoundField CreditAmount = new BoundField();
                CreditAmount.DataField = "Cr";
                CreditAmount.ItemStyle.Width = Unit.Percentage(15);
                //Item.ItemStyle.Wrap = true;
                CreditAmount.HeaderText = "Credit ";
                CreditAmount.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                grdChild.Columns.Add(CreditAmount);
                BoundField BalanceAmount = new BoundField();
                BalanceAmount.DataField = "Balance Amount";
                BalanceAmount.ItemStyle.Width = Unit.Percentage(15);
                BalanceAmount.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                //unit.ItemStyle.Wrap = true;
                BalanceAmount.HeaderText = "Balance";
                grdChild.Columns.Add(BalanceAmount);
                BoundField CrDr = new BoundField();
                CrDr.DataField = "Cr/Dr";
                CrDr.ItemStyle.Width = Unit.Percentage(5);
                CrDr.HeaderText = "Cr/Dr";
                grdChild.Columns.Add(CrDr);
                ImageButton imgShow = (ImageButton)e.Row.FindControl("imgShow");
                string strDate = string.Empty;

                DataView dv = dtMn.DefaultView;
                string de="LID =" + custID[ds-1].ToString();
                dv.RowFilter = de;
                DataTable df = dv.ToTable();
                if (df.Rows.Count > 0)
                {
                    grdChild.DataSource = dtMn;
                    grdChild.DataBind();
                }
                
                int LastCellPosition = e.Row.Cells.Count - 1;
                System.IO.StringWriter sw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
                grdChild.RenderControl(htw);
                string DivStart = "</td></tr><tr id=\"TR_Summmary" + e.Row.RowIndex.ToString() + "\" style=\"display: none; height: 1px;\"><td colspan=\"2\" style=\"width: 100%;\">";
                string DivBody = sw.ToString().Replace("<div>", "").ToString().Replace("</div>", "");
                //Response.Write(sw.ToString()+"<br/>");
                string DivEnd = "";
                string FullDIV = DivStart + DivBody + DivEnd;
                //Match color of div which we will expand base on row
                if (e.Row.RowIndex % 2 == 0)
                {  //set to regular row style
                    e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text + " " + FullDIV;
                }
                else
                {
                    //set to alternative row style
                    e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text + " " + FullDIV;
                }
                imgShow.Attributes.Add("onclick", "return expandDetailsInGrid('" + imgShow.ClientID + "','TR_Summmary" + e.Row.RowIndex.ToString() + "');");
            }
        }
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Attributes.Add("colspan", "2");
            e.Row.Cells.RemoveAt(1);
            e.Row.Cells[0].Style.Add("width", "100%");
            e.Row.Cells[0].Text = "Client Ledger Register From " + string.Format("{0:dd-MMM-yyyy}", Convert.ToDateTime(txtFromDate.Text)) + " to " + string.Format("{0:dd-MMM-yyyy}", Convert.ToDateTime(txtToDate.Text));
            e.Row.Cells[0].Style.Add("border-bottom", "solid 1px #818181");
            //e.Row.CssClass = "headtd";
        }
    }
    protected void btnChangeDate_Click(object sender, EventArgs e)
    {
        lid = string.Empty;
        lname = string.Empty;
        dtCustmr.Columns.Add("LID", typeof(string));
        dtCustmr.Columns.Add("LNAME", typeof(string));
        int rowcount = grdTDSClient.Rows.Count;
        for (int i = 1; i < rowcount; i++)
        {
            CheckBox chkopt = (CheckBox)grdTDSClient.Rows[i].FindControl("chkOpt");
            HiddenField hidLID = (HiddenField)grdTDSClient.Rows[i].FindControl("hidLID");
            Label ledName = (Label)grdTDSClient.Rows[i].FindControl("lblLedger");
            if (chkopt.Checked == true)
            {
                DataRow dr = dtCustmr.NewRow();
                dr["LID"] = hidLID.Value.ToString();
                dr["LNAME"] = ledName.Text.ToString();
                dtCustmr.Rows.Add(dr);
                lid += hidLID.Value.ToString() + ",";
                lname += ledName.Text + ",";
            }
        }
        BindGrid();
    }
    
    protected void grdChild_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView grdChild = (GridView)sender;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            double debit = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Dr"));     //e.Row.Cells[2].Text);
            double credit = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Cr"));
            double BalanceAmount = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Balance Amount"));
            double dblCurrentClosing = credit - debit;
            string strSortOrder = grdChild.DataKeys[e.Row.RowIndex].Values["Sortorder2"].ToString();
            e.Row.Cells[2].Text = string.Empty;
            e.Row.Cells[3].Text = string.Empty;
            e.Row.Cells[4].Text = string.Empty;
            e.Row.Cells[5].Text = string.Empty;


            if (strSortOrder != "7")
            {
                dblNetClosing = dblNetClosing + dblCurrentClosing;
            }



            if (strSortOrder != "1" && strSortOrder != "7")
            {

                if (dblCurrentClosing > 0)
                {
                    e.Row.Cells[3].Text = acntstng.GetCurrency(Math.Abs(dblCurrentClosing));
                }
                else if (dblCurrentClosing < 0)
                {
                    e.Row.Cells[2].Text = acntstng.GetCurrency(Math.Abs(dblCurrentClosing));
                }
            }


            
            if (Math.Abs(dblNetClosing) > 0)
            {
                e.Row.Cells[4].Text = acntstng.GetCurrency(Math.Abs(dblNetClosing));
            }

            if (dblNetClosing > 0)
            {
                e.Row.Cells[5].Text = "Cr";
            }
            else if (dblNetClosing < 0)
            {
                e.Row.Cells[5].Text = "Dr";
            }

            //if (strSortOrder == "1")
            //{
            //    e.Row.Cells[4].Text = acntstng.GetCurrency(Math.Abs(dblCurrentClosing));
            //}
            //else if (strSortOrder == "7")
            //{
            //    e.Row.Cells[4].Text = acntstng.GetCurrency(Math.Abs(dblNetClosing));
            //}
            //else
            //{
                
            //} 
        }
    }

    protected void grdTDSClient_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdTDSClient.PageIndex = e.NewPageIndex;
        BindCustomer();
        ChkSelectAll.Checked = false;
    }
    protected void btnDisplay_Click(object sender, EventArgs e)
    {
        lid = string.Empty;
        lname = string.Empty;
        dtCustmr.Columns.Add("LID", typeof(string));
        dtCustmr.Columns.Add("LNAME", typeof(string));
        int rowcount = grdTDSClient.Rows.Count;
        for (int i = 1; i < rowcount; i++)
        {
            CheckBox chkopt = (CheckBox)grdTDSClient.Rows[i].FindControl("chkOpt");
            HiddenField hidLID = (HiddenField)grdTDSClient.Rows[i].FindControl("hidLID");
            Label ledName = (Label)grdTDSClient.Rows[i].FindControl("lblLedger");
            if (chkopt.Checked == true)
            {
                DataRow dr = dtCustmr.NewRow();
                dr["LID"] = hidLID.Value.ToString();
                dr["LNAME"] = ledName.Text.ToString();
                dtCustmr.Rows.Add(dr);
                lid += hidLID.Value.ToString() + ",";
                lname += ledName.Text + ",";
                
            }
        }
            finyear = Session["finyear"].ToString();
            hidfinyear.Value = Session["finyear"].ToString();
            txtFromDate.Text = Convert.ToString("01/04/" + finyear);
            txtToDate.Text = "31/03/" + (Convert.ToInt32(finyear) + 1).ToString();
            BindGrid();
            pnlTDSClient.Visible =false ;
            pnlGrid.Visible =true ;
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }

    protected void DataList2_ItemBound(object sender, DataListItemEventArgs e)
    {
        GridView grd = (GridView)e.Item.FindControl("grdPrint");
        Label lblPrintAgeRange = (Label)e.Item.FindControl("lblPrintAgeRange");

        DataTable DTTempData = new DataTable(); //_GetOutstandingData(hidToDate.Value);
        DataView dv = DTTempData.DefaultView;
        string str = "AgeRange ='" + lblPrintAgeRange.Text + "'";
        dv.RowFilter = str;
        DataTable des = dv.ToTable();
        grd.DataSource = dv.ToTable();
        grd.DataBind();

        grd.RowDataBound += new GridViewRowEventHandler(grdPrint_RowDataBound);
        //imgShow.Attributes.Add("onclick", "return expandDetailsInGrid('" + imgShow.ClientID + "','" + grd.ClientID + "');");

    }
    protected void grdPrint_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView grdChild = (GridView)sender;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            double debitN = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Dr"));     //e.Row.Cells[2].Text);
            double creditN = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Cr"));
            double BalanceAmountN = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Balance Amount"));
            double dblCurrentClosingN = creditN - debitN;
            string strSortOrderN = grdChild.DataKeys[e.Row.RowIndex].Values["Sortorder2"].ToString();
            e.Row.Cells[2].Text = string.Empty;
            e.Row.Cells[3].Text = string.Empty;
            e.Row.Cells[4].Text = string.Empty;
            e.Row.Cells[5].Text = string.Empty;


            if (strSortOrderN != "7")
            {
                dblNetClosingN = dblNetClosingN + dblCurrentClosingN;
            }

           if (strSortOrderN != "1" && strSortOrderN != "7")
            {

                if (dblCurrentClosingN > 0)
                {
                    e.Row.Cells[3].Text = acntstng.GetCurrency(Math.Abs(dblCurrentClosingN));
                }
                else if (dblCurrentClosingN < 0)
                {
                    e.Row.Cells[2].Text = acntstng.GetCurrency(Math.Abs(dblCurrentClosingN));
                }
            }
            if (Math.Abs(dblNetClosingN) > 0)
            {
                e.Row.Cells[4].Text = acntstng.GetCurrency(Math.Abs(dblNetClosingN));
            }

            if (dblNetClosingN > 0)
            {
                e.Row.Cells[5].Text = "Cr";
            }
            else if (dblNetClosingN < 0)
            {
                e.Row.Cells[5].Text = "Dr";
            }
        }
    }

}